import 'package:event_bus/event_bus.dart';
import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:f_enjoy_plus/components/Header.dart';
import 'package:f_enjoy_plus/utils/eventBus.dart';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

class MyPage extends StatefulWidget {
  MyPage({super.key, required this.currentIndex});

  int currentIndex;

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final List<Map<String, dynamic>> menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
      "path": '/house',
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
      "path": '/myRepair',
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
      "path": '/visitor',
    },
  ];
  Map userInfo = {'avatar': '', 'nickName': '', 'id': ''};

  @override
  void didUpdateWidget(covariant MyPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      _fetchUserInfo();
    }
  }

  _fetchUserInfo() async {
    try {
      final res = await http.get('/userInfo');
      print(res);
      setState(() {
        userInfo = res;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<LoginEvent>().listen((event) {
      _fetchUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(title: '我的'),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [AppColors.primary, AppColors.primaryLight],
          ),
        ),
        child: ListView(
          padding: EdgeInsets.all(12),
          children: [
            Container(
              margin: EdgeInsets.only(bottom: 12),
              child: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(context, '/profile', arguments: userInfo);
                },
                child: Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(100),
                      child:
                          userInfo['avatar'] != ''
                              ? Image.network(
                                userInfo['avatar'],
                                width: 50,
                                height: 50,
                              )
                              : Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 50,
                                height: 50,
                              ),
                    ),
                    SizedBox(width: 12),
                    Text(
                      userInfo['nickName'] ?? '用户名',
                      style: TextStyle(color: AppColors.white),
                    ),
                    Spacer(),
                    Row(
                      children: [
                        Text('去完善信息', style: TextStyle(color: AppColors.white)),
                        Icon(
                          Icons.arrow_forward_ios,
                          color: AppColors.white,
                          size: 16,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppColors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: menuList.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () {
                      Get.toNamed(menuList[index]['path']);
                    },
                    child: SizedBox(
                      height: 48,
                      child: Row(
                        children: [
                          Image.asset(
                            menuList[index]['icon'],
                            width: 24,
                            height: 24,
                          ),
                          SizedBox(width: 12),
                          Text(
                            menuList[index]['title'],
                            style: TextStyle(color: AppColors.textPrimary),
                          ),
                          Spacer(),
                          Icon(
                            Icons.arrow_forward_ios,
                            color: AppColors.textPrimary,
                            size: 16,
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                TokenManager.instance.clearToken();
                Navigator.pushNamedAndRemoveUntil(
                  context,
                  '/login',
                  (route) => false,
                );
              },
              child: Text('退出登录'),
            ),
          ],
        ),
      ),
    );
  }
}
